import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_study/bean/CounterModel.dart';
import 'package:provider/provider.dart';

class ScanActivity extends StatefulWidget {
  String intentStr;

  ScanActivity(this.intentStr);

  @override
  _ScanActivityState createState() => _ScanActivityState();
}

class _ScanActivityState extends State<ScanActivity> {
  String _scanResultStr = "";

  //扫码
  Future _scan() async {
    //利用try-catch来进行异常处理
    try {
      //调起摄像头开始扫码
      String barcode = await BarcodeScanner.scan();
      setState(() {
        return this._scanResultStr = barcode;
      });
    } catch (e) {
      //如果没有调用摄像头的权限，则提醒
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        setState(() {
          return this._scanResultStr =
              'The user did not grant the camera permission!';
        });
      } else {
        setState(() {
          return this._scanResultStr = 'Unknown error: $e';
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.intentStr)),
      body: Column(
        children: <Widget>[
          RaisedButton(
            onPressed: () {
              _scan();
            },
            child: Text("扫码"),
          ),
          Text(_scanResultStr),
          RaisedButton(
            child: Text("改Provider值"),
            onPressed: () {
              Provider.of<CounterModel>(context).changeValue(12);
            },
          )
        ],
      ),
    );
  }
}
